﻿#region Copyright(C) 2018 FI Ltd. All rights reserved.
// ==================================================================================================
// Copyright(C) 2018 FI Ltd. All rights reserved.
//
// SYSTEM NAME	    : FI.Net Application Framework
// COMPONENT ID	    : FI.Core
// COMPONENT DESC   : FI.Net Core Foundation
//
// CREATED DATE/BY  : 18 Aug 2018 / Tian Mi
//
// REVISION HISTORY :	
// DATE/BY			SR#/CS/PM#/OTHERS		DESCRIPTION OF CHANGE
// ==================================================================================================
#endregion

using FI.Core.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace FI.Core.IoC
{
    internal class ReflectedServiceLocatorConfigurator : IServiceLocatorConfigurator
    {
        #region Fields
        private Dictionary<MapToAttribute, Type> mapToAttributes = null;
        private object syncHelper = new object();
        #endregion

        #region Properties
        public IAssemblyResolver AssemblyResolver { get; private set; }
        #endregion

        #region Constructors
        public ReflectedServiceLocatorConfigurator(IAssemblyResolver assemblyResolver)
        {
            Guard.ArgumentNotNull(assemblyResolver, "assemblyResolver");
            this.AssemblyResolver = assemblyResolver;
        }
        #endregion

        #region Public Methods
        public void Configure(IServiceLocator serviceLocator)
        {
            Guard.ArgumentNotNull(serviceLocator, "serviceLocator");
            foreach (var group in GetMapToAttributes().Keys.GroupBy(attribute => attribute.RegisteredType))
            {
                if (serviceLocator.IsRegistered(group.Key))
                {
                    continue;
                }
                foreach (var group1 in group.GroupBy(a => a.Name))
                {
                    MapToAttribute attribute = group1.OrderByDescending(a => a.Quality).First();
                    serviceLocator.Register(attribute.RegisteredType, mapToAttributes[attribute],attribute.Name, string.IsNullOrEmpty(attribute.Name), attribute.Lifetime);
                }
            }
        }

        public Dictionary<MapToAttribute, Type> GetMapToAttributes()
        {
            if (null != mapToAttributes)
            {
                return mapToAttributes;
            }
            lock (syncHelper)
            {
                if (null != mapToAttributes)
                {
                    return mapToAttributes;
                }
                mapToAttributes = new Dictionary<MapToAttribute, Type>();
                foreach (Assembly assembly in this.AssemblyResolver.GetAssemblies())
                {
                    try
                    {
                        foreach (Type type in assembly.GetTypes())
                        {
                            foreach (MapToAttribute attribute in AttributeAccessor.GetAttributes<MapToAttribute>(type, false))
                            {
                                mapToAttributes.Add(attribute, type);
                            }
                        }
                    }
                    catch (ReflectionTypeLoadException)
                    {
                        continue;
                    }
                }
            }
            return mapToAttributes;
        }

        public  T CreateInstance<T>(params object[] args)
        {
            MapToAttribute mapToAttribute = (from attribute in GetMapToAttributes().Keys
                                             where attribute.RegisteredType == typeof(T)
                             orderby attribute.Quality descending
                             select attribute).FirstOrDefault();
            if (null != mapToAttribute)
            {
                return (T)Activator.CreateInstance(mapToAttributes[mapToAttribute], args);
            }
            return default(T);
        }
        #endregion
    }
}
